package com.wande.dataplatform.filecollection.domain.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据校验结果DTO
 *
 * @author wande
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ValidationResult implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 是否通过校验
     */
    private Boolean valid;

    /**
     * 错误信息列表
     */
    @Builder.Default
    private List<ValidationError> errors = new ArrayList<>();

    /**
     * 添加错误
     */
    public void addError(ValidationError error) {
        if (this.errors == null) {
            this.errors = new ArrayList<>();
        }
        this.errors.add(error);
        this.valid = false;
    }

    /**
     * 创建成功结果
     */
    public static ValidationResult success() {
        return ValidationResult.builder()
            .valid(true)
            .errors(new ArrayList<>())
            .build();
    }

    /**
     * 创建失败结果
     */
    public static ValidationResult failure(String fieldName, String errorMessage) {
        ValidationResult result = new ValidationResult();
        result.setValid(false);
        result.addError(ValidationError.builder()
            .fieldName(fieldName)
            .errorMessage(errorMessage)
            .build());
        return result;
    }

    /**
     * 校验错误信息
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ValidationError implements Serializable {
        private static final long serialVersionUID = 1L;

        /**
         * 字段名
         */
        private String fieldName;

        /**
         * 错误类型
         */
        private String errorType;

        /**
         * 错误消息
         */
        private String errorMessage;

        /**
         * 字段值
         */
        private Object fieldValue;
    }
}
